<?php

namespace addons\shopro\controller\commission;

use addons\shopro\model\commission\Agent as AgentModel;
use addons\shopro\model\commission\Level;
use addons\shopro\model\commission\Reward;
use addons\shopro\model\User;
use addons\shopro\library\commission\Agent as AgentLibrary;
use addons\shopro\library\commission\Config as ConfigLibrary;
use app\admin\model\shopro\commission\School as SchoolModel;
use app\admin\model\shopro\commission\Education as EducationModel;
use app\admin\model\shopro\commission\Level as LevelModel;
use addons\shopro\model\Share as ShareModel;
use app\common\library\Sms;
use addons\shopro\model\commission\Order as OrderModel;
class Agent extends Commission
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * 分销商详情
     */
    public function info()
    {
        $user = $this->auth->getUserinfo();
        $agent = new AgentLibrary($user['id']);
        $agentInfo = $agent->getAgentInfo();
        // 是否显示申请信息入口
        $agentInfo['agent_form'] = $this->config->getAgentForm()  == 0 ? false : true;
        $agentInfo['upgrade_display'] = $this->config->isUpgradeDisplay();
        // 未满足成为分销商条件
        // if($agentInfo['status'] == null) {
        $agentInfo['become_agent'] = $this->config->getBecomeAgentEvent();
        // }
        if ($agent->isAgentAvaliable()) {
            $agentInfo['data']['agent_level'] = $agent->getAgentLevelInfo();
            // 待入账佣金
            $agentInfo['data']['delay_money'] = $agent->getAgentDelayMoney();
            // 直推佣金
            $agentInfo['data']['direct_money'] = $agent->getAgentDirectMoney();
            // 间推佣金
            $agentInfo['data']['inter_money'] = $agent->getAgentInterMoney();
            // 获取等级
            $agentInfo['data']['level_list'] = LevelModel::where("level",'lt',$agentInfo['data']['level'])->select();
            if($agentInfo['data']['apply_info']){
                $apply_info = json_decode($agentInfo['data']['apply_info'],true);
                $apply_info_new = [];
                for($i = 0;$i < count($apply_info);$i++){
                    $apply_info_new[$apply_info[$i]['key']] = $apply_info[$i]['value'];
                }
            }
            $agentInfo['data']['apply_info'] = $apply_info_new;
        }

        $this->success('获取成功', $agentInfo);
    }



    /**
     * 我的团队
     *
     * @return void
     */
    public function team(){
        $params = $this->request->get();
        extract($params);
        if(isset($params['user_id']) && $params['user_id']){
            $user_id = $params['user_id'];
        } else {
            $user_id = $this->auth->id;
        }
        $user = User::where("id",$user_id)->find();
        if (isset($id)) {
            // 查询 id 是否是当前用户的下级
            $childUser = User::where('parent_user_id', $user['id'])->where('id', $id)->count();
            if (!$childUser) {
                $this->error('用户不存在');
            }
        } else {
            $id = $user['id'];
        }
        $where = ['parent_agent_id'=>$id];
        if(isset($params['status']) && $params['status']){
            $where['status'] = $params['status'];
        } else {
            $where['status'] = array("neq",'waitpay');
        }
        if(isset($params['level']) && $params['level']){
            $where['level'] = $params['level'];
        }
        if(isset($params['keyword'])){
            $where['apply_info'] = array("like","%".$params['keyword']."%");
        }
        $teams = AgentModel::where($where)->with(['user','level'])->order('order_money', 'desc')->paginate($per_page ?? 10);
        // 分销等级
        $level_where = [];
        $agent = new AgentLibrary($user['id']);
        $agentInfo = $agent->getAgentInfo();
        $agent_level = $agentInfo['data']['level'];
        if($agent_level < 4){
            $level_where['level'] = array("lt",4);
        }
        $level_list = LevelModel::where($level_where)->select();
        for($i = 0;$i < count($level_list);$i++){
            $where['level'] = $level_list[$i]['level'];
            $level_list[$i]['num'] = AgentModel::where($where)->count();
        }
        unset($where['level']);
        $all_num = AgentModel::where($where)->count();
        array_unshift($level_list,["level"=>'','name'=>'全部','num'=>$all_num]);
        // 我的上级
        $parentUser = '';
        if ($user['parent_user_id']) {
            $parentUser = AgentModel::where('user_id', $user['parent_user_id'])->with(['user','level'])->find();
        }
        $this->success('我的团队', [
            'user'=>$user,
            'parent_user' => $parentUser,
            'teams' => $teams,
            'level_list' => $level_list,
        ]);
    }
    public function team_old()
    {
        $params = $this->request->get();
        extract($params);
        $this->auth->setAllowFields(['id', 'username', 'nickname', 'mobile', 'avatar', 'score', 'money', 'parent_user_id']);
        $user = $this->auth->getUserinfo();

        if (isset($id)) {
            // 查询 id 是否是当前用户的下级
            $childUser = User::where('parent_user_id', $user['id'])->where('id', $id)->count();
            if (!$childUser) {
                $this->error('用户不存在');
            }
        } else {
            $id = $user['id'];
        }

        $fields = 'id,nickname,avatar,parent_user_id,child_user_count_1,createtime';
        $teams = User::where('parent_user_id', $id)->with(['agent' => function ($query) {
            $query->avaliable()->with(['level' => function ($query) {
                $query->field('level,name,image');
            }]);
        }])
            ->field($fields)
            ->order('createtime', 'asc')
            ->paginate($per_page ?? 10);

        $parentUser = null;
        if ($user['parent_user_id']) {
            $parentUser = User::where('id', $user['parent_user_id'])->field('id,nickname,avatar')->find();
        }

        $this->success('我的团队', [
            'teams' => $teams,
            'parent_user' => $parentUser
        ]);
    }



    /**
     * 分销商申请表单
     */
    public function agentForm()
    {
        $config = new ConfigLibrary();
        $agentForm = $config->getAgentForm();
        if (!$agentForm) {
            $this->error('系统未开启分销商自助申请');
        }
        $backgroundImage = cdnurl($agentForm['background_image'], true);
        // 系统开启完善资料
        $agent = new AgentLibrary($this->auth->id);
        list($applyStatus, $applyInfo,$agentInfo) = $this->checkApplyStatus($agent);
        // 合并已有表单信息
        if ($applyInfo) {
            $userApplyInfoName = array_column($applyInfo, 'name');
            foreach ($agentForm['content'] as &$form) {
                if (in_array($form['name'], $userApplyInfoName) && $applyInfo[array_search($form['name'], $userApplyInfoName)]['type'] === $form['type']) {
                    $form = $applyInfo[array_search($form['name'], $userApplyInfoName)];
                }
                if ($form['type'] === 'image' && isset($form['value'])) {
                    $form['value'] = cdnurl($form['value'], true);
                }
            }
        }
        // 获取学校
        $school_list = SchoolModel::where("status",1)->select();
        // 获取学历
        $education_list = EducationModel::where("status",1)->select();
        // 获取分享人
        $level_where = [];
        $share = '';
        if($applyStatus){
            $share = (new ShareModel)->checkLatestShareLogByAgent($this->auth->id,'index');
            if($share){
                $share_agent = AgentModel::where("user_id",$share['share_id'])->find();
                if($share_agent){
                    $level_where['level'] = $share['level'] && $share['level'] < $share_agent['level'] ?  $share['level'] : array('lt',$share_agent['level']);
                } else {
                    $share = '';
                }
            }
        } else {
            $level_where['level'] = $agentInfo['data']['level'];
        }
        
         // 获取等级
        $level_list = LevelModel::where($level_where)->select();
        $data = [
            'apply_protocol' =>  $config->getApplyProtocol(),
            'apply_status' => $applyStatus,
            'apply_info' => $applyInfo,
            'background_image' => $backgroundImage,
            'school_list' => $school_list,
            'education_list' => $education_list,
            'level_list' => $level_list,
            'status' => $agentInfo['status'],
            'share' => $share
        ];

        $this->success('申请表单', $data);
    }

    /**
     * 提交表单申请
     * 
     */
    public function applyForm()
    {
        $config = new ConfigLibrary();
        $agentForm = $config->getAgentForm();
        if (!$agentForm) {
            $this->error('系统未开启分销商自助申请');
        }
        $agent = new AgentLibrary($this->auth->id);

        // 提交资料
        \think\Db::transaction(function () use ($agent, $agentForm) {
            list($applyStatus, $applyInfo) = $this->checkApplyStatus($agent);

            if (!$applyStatus) {
                $this->error('您暂时不能申请');
            }
            $post = $this->request->post();
            $userApplyInfo = $post['data'];
            $ret = Sms::check($post['mobile'], $post['code'], 'register');
            if (!$ret) {
                $this->error(__('验证码不正确'));
            }
            $agentInfo = $agent->getAgentInfo();
        
            if ($agentInfo['status'] == AgentLibrary::AGENT_STATUS_NEEDINFO) {
                $agent->becomeAgent(json_encode($userApplyInfo, JSON_UNESCAPED_UNICODE));
            } elseif ($applyStatus) {
                $agent->agent->apply_info = json_encode($userApplyInfo, JSON_UNESCAPED_UNICODE);
                \addons\shopro\library\commission\Log::write($agent->user->id, 'agent', ['type' => 'apply_info']);
            }
            if($agent->agent->pay_status == 0){
                // 获取等级
                $level_info = LevelModel::where("level",$post['level'])->find();
                if($level_info['commission_rules']['price']){
                    $agent->agent->total_fee = $level_info['commission_rules']['price'];
                    $agent->agent->order_sn = self::getSn($this->auth->id);
                    $agent->agent->pay_status = 0;
                    $agent->agent->status = AgentLibrary::AGENT_STATUS_WAITPAY;
                } else {
                    $agent->agent->pay_status = 1;
                    $agent->agent->status = AgentLibrary::AGENT_STATUS_PENDING;
                }
            }
            $agent->agent->parent_agent_id = $post['share_id'];
            $agent->agent->level = $post['level'];
            $agent->agent->apply_num += 1;
            $agent->agent->info_status  = AgentLibrary::INFO_STATUS_COMPLETED;
            $agent->agent->save();
        });
        $this->success('提交成功', $agent->agent);
    }

    public function ranking()
    {
        $params = $this->request->get();
        if(isset($params['date_type'])){
            $agents = OrderModel::getRanking($params);
        } else {
            $agents = AgentModel::getRanking($params);
        }
       

        $this->success('分销商排行', $agents);
    }

    public function level()
    {
        if ($this->config->isUpgradeDisplay()) {
            $data['level'] = Level::order('level asc')->select();
            $data['commission_level'] = $this->config->getCommissionLevel();
            $this->success('升级进度', $data);
        } else {
            $this->error('未开启升级显示');
        }
    }

    private function checkApplyStatus($agent)
    {
        $applyStatus = false;  // 提交状态
        $agentInfo = $agent->getAgentInfo();
        $applyInfo = json_decode($agentInfo['data']['apply_info'] ?? '', true);
        switch ($agentInfo['status']) {
            case AgentLibrary::AGENT_STATUS_WAITPAY:  // 待支付，可以继续完善资料
                $applyStatus = true;
                break;
            case AgentLibrary::AGENT_STATUS_NEEDINFO:  // 分销商条件已达成，只剩资料未完善
                $applyStatus = true;
                break;
            case AgentLibrary::AGENT_STATUS_NORMAL:   // 分销商状态正常 视情况可更新信息
                $infoStatus = $agent->agent->info_status;
                if ($infoStatus === AgentLibrary::INFO_STATUS_NONE) {   // 补全信息
                    $applyStatus = true;
                } else if ($infoStatus === AgentLibrary::INFO_STATUS_REJECT) {    // 修改信息
                    $applyStatus = true;
                }
                break;
                //  用户资料被驳回 需要做信息合并 重新提交
            case AgentLibrary::AGENT_STATUS_REJECT:
                $applyStatus = true;
                break;
        }
        if($applyInfo){
            $applyInfo[] = ["key"=>'level',"value"=>$agentInfo['data']['level']];
            $applyInfo[] = ["key"=>'share_id',"value"=>$agentInfo['data']['parent_agent_id'] ? $agentInfo['data']['parent_agent_id'] : ''];
        }
        return [$applyStatus, $applyInfo,$agentInfo];
    }
     // 获取订单号
    public static function getSn($user_id)
    {
        $rand = $user_id < 9999 ? mt_rand(100000, 99999999) : mt_rand(100, 99999);
        $order_sn = date('Yhis') . $rand;

        $id = str_pad($user_id, (24 - strlen($order_sn)), '0', STR_PAD_BOTH);

        return 'TA' . $order_sn . $id;
    }
    // 审核
    public function examine(){
        $params = $this->request->post();
        extract($params);
        $agent = new \addons\shopro\library\commission\Agent($params['user_id']);
        if (!$agent->agent) {
            $this->error('未找到分销商');
        }
        $status = $params['status'] ;
        if ($status === 'normal' && $agent->user->parent_user_id === 0 && $agent->agent->parent_agent_id !== 0) {
            $agent->user->parent_user_id = $agent->agent->parent_agent_id;
            $agent->user->save();
            \addons\shopro\library\commission\Log::write($agent->agent->parent_agent_id, 'share', ['user' => $agent->user], ['oper_type' => 'user', 'oper_id' => $agent->user->id]);
        }
        $agent->agent->save(['status'=>$status]);
        \addons\shopro\library\commission\Log::write($agent->agent->user_id, 'agent', ['type' => 'status','status'=>$status], ['oper_type' => 'user', 'oper_id' => $this->auth->id]);
        $agent_l = new \addons\shopro\library\commission\Agent($agent->agent->user_id);
        $agent_l->asyncAgentUpgrade($agent->agent->user_id);
        $this->success('审核成功', $agent);
    }
}
